package com.framework.utils.httpClient;
import com.framework.exception.RRException;
import com.framework.utils.jiufu.StringUtils;
import com.framework.utils.pay.suixingfu.horfu.util.JsonUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import sun.misc.BASE64Encoder;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 功能描述: 系统自动登录返回sessionId
 *
 * @author ck
 * @date 2018/11/28 11:33
 */
public class HttpLogin {

	private final static String V_CODE_URL = "http://route.showapi.com/184-5";

	private final static String SHOW_API_APPID = "82345";

	private final static String SHOW_API_SIGN = "6610771046e542d6aa10f0302afefc68";

	private final static String TYPE_ID = "34";



	public static String httpsKaYouImgBase64(String sessionId,String imgUrl){
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		StringBuffer buffer = null;
		byte[] by = new byte[1024];
		try{
			//创建SSLContext
			SSLContext sslContext = SSLContext.getInstance("SSL");
			TrustManager[] tm={new MyX509TrustManager()};
			//初始化
			sslContext.init(null, tm, new java.security.SecureRandom());
            //获取SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(imgUrl);
			HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
			conn.setDoOutput(true); //设置输入流采用字节流
			conn.setDoInput(true);  //设置输出流采用字节流
			conn.setUseCaches(false); //设置缓存
			conn.setRequestMethod("GET");
			//登录添加头的信息
			conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
			conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
			conn.setRequestProperty("Cache-Control","max-age=0");
			conn.setRequestProperty("Connection","keep-alive");
			conn.setRequestProperty("Cookie",sessionId);
			conn.setRequestProperty("Host","vip.cardinfo.com.cn");
			conn.setRequestProperty("Upgrade-Insecure-Requests","1");
			conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");
			//设置当前实例使用的SSLSoctetFactory
			conn.setSSLSocketFactory(ssf);
			conn.connect();
			//读取服务器端返回的内容
			InputStream is = conn.getInputStream();
			// 将内容读取内存中
			int len = -1;
			while ((len = is.read(by)) != -1) {
				data.write(by, 0, len);
			}
			// 关闭流
			is.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return "data:image/png;base64,"+encoder.encode(data.toByteArray());
	}

	/**
	 * 乐刷得到验证码的base64
	 * @param sessionId
	 * @param imgUrl
	 * @return
	 */
	public static String httpsLeShuaImgBase64(String sessionId,String imgUrl){
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		StringBuffer buffer = null;
		byte[] by = new byte[1024];
		try{
			//创建SSLContext
			SSLContext sslContext = SSLContext.getInstance("SSL");
			TrustManager[] tm={new MyX509TrustManager()};
			//初始化
			sslContext.init(null, tm, new java.security.SecureRandom());
            //获取SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(imgUrl);
			HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
			conn.setDoOutput(true); //设置输入流采用字节流
			conn.setDoInput(true);  //设置输出流采用字节流
			conn.setUseCaches(false); //设置缓存
			conn.setRequestMethod("GET");
			//登录添加头的信息
			conn.setRequestProperty("Cookie",sessionId);
			//设置当前实例使用的SSLSoctetFactory
			conn.setSSLSocketFactory(ssf);
			conn.connect();
			//读取服务器端返回的内容
			InputStream is = conn.getInputStream();
			// 将内容读取内存中
			int len = -1;
			while ((len = is.read(by)) != -1) {
				data.write(by, 0, len);
			}
			// 关闭流
			is.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return "data:image/png;base64,"+encoder.encode(data.toByteArray());
	}

	/**
	 * 登录乐刷账户
	 * @param requestUrl
	 * @param sessionId
	 * @param requestMethod
	 * @param outputStr
	 * @return
	 */
	public static String httpsLeShuaLogin(String requestUrl,String sessionId,String requestMethod,String outputStr){
		StringBuffer buffer = null;
		try{
			//创建SSLContext
			SSLContext sslContext = SSLContext.getInstance("SSL");
			TrustManager[] tm={new MyX509TrustManager()};
			//初始化
			sslContext.init(null, tm, new java.security.SecureRandom());
            //获取SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
			conn.setDoOutput(true); //设置输入流采用字节流
			conn.setDoInput(true);  //设置输出流采用字节流
			conn.setUseCaches(false); //设置缓存
			conn.setRequestMethod(requestMethod);
			//登录添加头的信息
			conn.setRequestProperty("Cookie",sessionId);
			//设置当前实例使用的SSLSoctetFactory
			conn.setSSLSocketFactory(ssf);
			conn.connect();
			//往服务器端写内容
			if(null != outputStr){
				OutputStream os = conn.getOutputStream();
				os.write(outputStr.getBytes(StandardCharsets.UTF_8));
				os.close();
			}
			//读取服务器端返回的内容
			InputStream is = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
			BufferedReader br = new BufferedReader(isr);
			buffer = new StringBuffer();
			String line = null;
			while((line = br.readLine()) != null){
				buffer.append(line);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return buffer.toString();
	}

	/**
	 * 根据base64识别验证码
	 * @param base64
	 * @return
	 */
	public static String getImgView(String base64,String typeId){
		base64 = URLEncoder.encode(base64);
		String parms = "showapi_appid="+SHOW_API_APPID+"&showapi_sign="+SHOW_API_SIGN+"&img_base64="+base64+"&typeId="+typeId;
		String res = HttpClientUtil.doGet(V_CODE_URL,parms);
		if(StringUtils.isNotBlank(res)){
			//结果对Json解析
			Map<String,Object> map = JsonUtils.fromJson(res);
			Object obj = map.get("showapi_res_body");
			String resBody = obj.toString();
			Map<String,Object> resBodyMap = JsonUtils.fromJson(resBody);
			String retCode = resBodyMap.get("ret_code").toString();
			//成功
			if(StringUtils.equals(retCode,"0")){
				String result = resBodyMap.get("Result").toString();
				return result;
			}
		}
		return null;
	}

	/*
	 * 卡友自动登录请求
	 * 请求地址、请求方法、参数
	 * */
	public static String httpsKaYouLogin(String requestUrl,String sessionId,String requestMethod,String outputStr){
		StringBuffer buffer = null;
		try{
			//创建SSLContext
			SSLContext sslContext = SSLContext.getInstance("SSL");
			TrustManager[] tm={new MyX509TrustManager()};
			//初始化
			sslContext.init(null, tm, new java.security.SecureRandom());
            //获取SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
			conn.setDoOutput(true); //设置输入流采用字节流
			conn.setDoInput(true);  //设置输出流采用字节流
			conn.setUseCaches(false); //设置缓存
			conn.setRequestMethod(requestMethod);
			//登录添加头的信息
			conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
			conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
			conn.setRequestProperty("Cache-Control","max-age=0");
			conn.setRequestProperty("Connection","keep-alive");
			conn.setRequestProperty("Cookie",sessionId);
			conn.setRequestProperty("Host","vip.cardinfo.com.cn");
			conn.setRequestProperty("Referer","https://vip.cardinfo.com.cn/agent/operatorLogin.action");
			conn.setRequestProperty("Upgrade-Insecure-Requests","1");
			conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");
			//设置当前实例使用的SSLSoctetFactory
			conn.setSSLSocketFactory(ssf);
			conn.connect();
			//往服务器端写内容
			if(null != outputStr){
				OutputStream os = conn.getOutputStream();
				os.write(outputStr.getBytes(StandardCharsets.UTF_8));
				os.close();
			}
			//读取服务器端返回的内容
			InputStream is = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
			BufferedReader br = new BufferedReader(isr);
			buffer = new StringBuffer();
			String line = null;
			while((line = br.readLine()) != null){
				buffer.append(line);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return buffer.toString();
	}

	/**
	 * 卡友自动登录
	 * @param account 账号
	 * @param password 密码
	 * @param loginUrl 登录地址
	 * @param imgCodeUrl 二维码地址
	 * @return
	 */
	public static String kaYouLogin(int loginFre,String account,String password,String loginUrl,String imgCodeUrl,String type){

		try{
			//获取网站的sessionId
			String sessionId = HttpSessionId.geSessionId(imgCodeUrl);
			if(StringUtils.isNotBlank(sessionId)){
				//获取图片的验证码，Cookie 必须都为一致
				String imgBase = httpsKaYouImgBase64(sessionId,imgCodeUrl);
				//识别验证码
				String vCode = getImgView(imgBase,"34");

				String res = httpsKaYouLogin(loginUrl,sessionId,"POST","username="+account+"&password="+password+"&randomCode="+ vCode);
				Document doc2 = Jsoup.parse(res);

				String str=doc2.getElementsByClass("errorMessage").toString();

				if(str!=null && str.contains("<span>")){
					throw new RRException("9000",str.substring(str.indexOf("<span>")+6,str.lastIndexOf("</span>")));
				}

				System.out.println(res);
				if(StringUtils.isNotBlank(res)){
					loginFre++;
					//循环登录10次，直到成功为止
					if(loginFre == 10){
						return  null;
					}
					//判断是否登录成功 关键字 你好，卡友合伙人
					boolean isLogin = res.contains(type);
					//登录成功的
					if(isLogin){
						return  sessionId;
					}else{
						kaYouLogin(loginFre,account,password,loginUrl,imgCodeUrl,type);
					}
				}
			}
		} catch (Exception e) {
			throw new RRException("9000",e.getMessage());
		}
		return  null;
	}



	/**
	 * 乐刷自动登录
	 * @param loginFre 登录次数
	 * @param account 账号
	 * @param password 密码
	 * @param loginUrl 登录地址
	 * @param imgCodeUrl 二维码地址
	 * @return
	 */
	public static String leShuaLogin(int loginFre,String account,String password,String loginUrl,String imgCodeUrl){
		try{
			//获取网站的sessionId
			String sessionId = HttpSessionId.geSessionId(imgCodeUrl);
			if(StringUtils.isNotBlank(sessionId)){
				//获取图片的验证码，Cookie 必须都为一致,方可通过登录
				String imgBase = httpsLeShuaImgBase64(sessionId,imgCodeUrl);
				String vCode = getImgView(imgBase,"34"); //识别验证码
				String res = httpsLeShuaLogin(loginUrl,sessionId,"POST","usercode="+account+"&password="+password+"&validateCode="+ vCode);
				System.out.println(res);
				if(StringUtils.isNotBlank(res)){
					loginFre++;
					//循环登录10次，直到成功为止
					if(loginFre == 10){
						return  null;
					}
					//解析JSON数据
					Map<String,Object> obj = JsonUtils.fromJson(res);
					Object codeObj = obj.get("code");
					if(codeObj == null){
						leShuaLogin(loginFre,account,password,loginUrl,imgCodeUrl);
					}else{
						if(StringUtils.equals("0",codeObj.toString())){
							return  sessionId;
						}else{
							leShuaLogin(loginFre,account,password,loginUrl,imgCodeUrl);
						}
					}
				}
			}
		} catch (Exception e) {
			return null;
		}
		return  null;
	}

	/**
	 * 乐刷大POS登录
	 * @param loginFre 登录次数
	 * @param account 账号
	 * @param password 密码
	 * @param loginUrl 登录地址
	 * @param imgCodeUrl 二维码地址
	 * @return
	 */
	public static String leShuaBigLogin(int loginFre,String account,String password,String loginUrl,String imgCodeUrl){
		try{
			//获取网站的sessionId
			String sessionId = HttpSessionId.geSessionId(imgCodeUrl);
			if(StringUtils.isNotBlank(sessionId)){
				//获取图片的验证码，Cookie 必须都为一致,方可通过登录
				String imgBase = httpsLeShuaImgBase64(sessionId,imgCodeUrl);
				String vCode = getImgView(imgBase,"34"); //识别验证码
				String res = httpsLeShuaLogin(loginUrl,sessionId,"POST","username="+account+"&password="+password+"&authCode="+ vCode);
				if(StringUtils.isNotBlank(res)){
					loginFre++;
					//循环登录10次，直到成功为止
					if(loginFre == 10){
						return  null;
					}
					//解析JSON数据
					Map<String,Object> obj = JsonUtils.fromJson(res);
					Object codeObj = obj.get("code");
					if(codeObj == null){
						leShuaBigLogin(loginFre,account,password,loginUrl,imgCodeUrl);
					}else{
						if(StringUtils.equals("0",codeObj.toString())){
							//获取token
							String data = obj.get("data").toString();
							Map<String,Object> dataMap = JsonUtils.fromJson(data);
							return  dataMap.get("token").toString();
						}else{
							leShuaBigLogin(loginFre,account,password,loginUrl,imgCodeUrl);
						}
					}
				}
			}
		} catch (Exception e) {
			return null;
		}
		return  null;
	}

	public static String ruiHeBaoLogin(int loginFre,String account,String password,String loginUrl,String imgCodeUrl){
		try{
			//获取网站的sessionId
			String sessionId = HttpSessionId.geSessionId("https://mpos.ruiyinxin.com/qtfr/login/login.jsp");
			if(StringUtils.isNotBlank(sessionId)){
				//获取图片的验证码，Cookie 必须都为一致,方可通过登录
				String imgBase = httpsLeShuaImgBase64(sessionId,imgCodeUrl);
				String vCode = getImgView(imgBase,"35"); //识别验证码
				//循环登录10次，直到成功为止
				if(loginFre == 2){
					return  null;
				}
				String res = httpsLeShuaLogin(loginUrl,sessionId,"POST","loginname="+account+"&password="+password+"&validateCode="+ vCode);
				if(StringUtils.isNotBlank(res)){
					loginFre++;
					//解析JSON数据
					Map<String,Object> obj = JsonUtils.fromJson(res);
					Object success = obj.get("success");
					if(success == null){
						ruiHeBaoLogin(loginFre,account,password,loginUrl,imgCodeUrl);
					}else{
						if(StringUtils.equals("true",success.toString())){
							return  sessionId;
						}else{
							ruiHeBaoLogin(loginFre,account,password,loginUrl,imgCodeUrl);
						}
					}
				}
			}
		} catch (Exception e) {
			return null;
		}
		return  null;
	}

	public static void main(String[] args) {
		//System.out.print(ruiHeBaoLogin(1,"5000287056","983778d7ff0acf77e26c0451ac5c84c4","https://mpos.ruiyinxin.com/qtfr/users/users.do?method=checkLogin","https://mpos.ruiyinxin.com/qtfr/login/Kaptcha.jpg"));
		//String code = "r8qv";
		//String res = httpsKaYouLogin("https://vip.cardinfo.com.cn/agent/operatorLogin.action","POST","username=13852290324&password=asd123456.&randomCode="+code);
		//System.out.print(kaYouLogin(0,"13852290324","asd123456.","https://vip.cardinfo.com.cn/agent/operatorLogin.action","https://vip.cardinfo.com.cn/agent/getVerificationCode.action"));
		//shanYinLogin(0,"19046716","Syz123456.","https://sympos.umfintech.com/mpos-web/login!applicationLogin.action","");
	}

	public static String shanYinLogin(int loginFre, String userName, String password, String loginUrl, String success) {
		String sessionId;
		try {
			sessionId= HttpSessionId.geSessionId("https://sympos.umfintech.com/mpos-web/login.action");
			if (StringUtils.isNotBlank(sessionId)) {
				if (loginFre == 2) {
					return null;
				}

				String res = httpsKaYouLogin(loginUrl, sessionId, "POST", "24OPTYPE%24=infoSystemLogin&LOGINIP=172.16.158.53&ROOTPath=%2Fmpos-web&username="+userName+"&password="+password);

				if(StringUtils.isNotBlank(res)){
					loginFre++;
					//解析JSON数据
					if(res.contains(success)){
						return sessionId;
					}else {
						shanYinLogin(loginFre,userName,password,loginUrl,success);
					}
				}

			}
		}catch (Exception e){
			return null;
		}
		return null;
	}


	private static String shanYinLoginHttp(String loginUrl,String username,String password,String sessionId) throws IOException {
		MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, sessionId, Charset.defaultCharset());
		multipartEntity.addPart("username", new StringBody("username", Charset.forName("UTF-8")));
		multipartEntity.addPart("operator", new StringBody("password", Charset.forName("UTF-8")));


		HttpPost request = new HttpPost(loginUrl);
		request.setEntity(multipartEntity);
		request.addHeader("Content-Type", "Content-Disposition: form-data; boundary=------------------------------0ea3fcae38ff");

		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = httpClient.execute(request);

		InputStream is = response.getEntity().getContent();
		BufferedReader in = new BufferedReader(new InputStreamReader(is));
		StringBuffer buffer = new StringBuffer();
		String line = "";
		while ((line = in.readLine()) != null)
		{
			buffer.append(line);
		}

		return buffer.toString();

	}

}
